#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef UNIX
# include <unistd.h>
#endif

#include "core.h"
#include "log.h"

void help()
{
    printf("Yaupspe is a PSP Emulator.\n");
    printf("It actually supports PBP, ELF and ISO files.\n\n");
    printf("Usage: yaupspe [OPTIONS] [-h|--help] [--usage] [-d|--dbg] FILE\n");
    printf("Where FILE is a file to load supported by Yaupspe.\n\n");
    printf("Recognized options:\n");
    printf("-h, --help                writes this help\n");
    printf("-d, --debug               opens the ncurses debugger if enabled at compile time (UNIX only)\n");
    printf("-m, --memory 0xADDRESS    loads a raw executable at address ADDRESS\n");
    printf("-lLVL, --debug-level LVL  sets the debug level to LVL\n\n");
    printf("Where LVL is one of these (each level includes the previous):\n");
    printf("- 0: nothing prints\n");
    printf("- 1: errors\n");
    printf("- 2: warnings\n");
    printf("- 3: debug\n");
    printf("- 4: trace\n");
    printf("- 5: full\n\n");
    printf("Project page: http://code.google.com/p/yaupspe/\n");
    exit(0);
}

void invldopt(char *option)
{
    printf("Option %s not recognized.\n", option);
    printf("Use --help for an option list.\n");
    exit(1);
}

void dbglevel(s32 c)
{
    if (c >= '0' && c <= '9')
        debug_level = (DbgLvl)(c - '0' - 1);
    else {
        printf("Not recognized debug level '%c'\n", c);
        help();
    }
}

s32 main(s32 argc, char *argv[])
{
    s32 i;
    s32 f = -1;

    for (i = 1; i < argc; i++)
    {
        /* Long option */
        if (argv[i][0] == '-' && argv[i][1] == '-')
        {
            if (strcmp(argv[i], "--help") == 0)
                help();
            else if (strcmp(argv[i], "--dbg") == 0)
                isDbg = 1;
            else if (strcmp(argv[i], "--debug-level") == 0)
                dbglevel(argv[++i][0]);
            else if (strcmp(argv[i], "--memory") == 0)
                sscanf(argv[++i], "0x%08x", &bootAddr);
            else
                invldopt(argv[i]);
        }
        /* Short option */
        else if (argv[i][0] == '-')
        {
            switch (argv[i][1])
            {
            case 'h':
                help();
                break;

            case 'd':
                isDbg = 1;
                break;

            case 'l':
                dbglevel(argv[i][2]);
                break;

            case 'm':
                sscanf(argv[++i], "0x%08x", &bootAddr);
                break;

            default:
                invldopt(argv[i]);
                break;
            }
        }
        /* File to load */
        else
            f = i;
    }

    if (f != -1)
    {
        logInitTh();
        core_start(argv[f]);
        logFreeTh();
    }
    else
        help();

    return 0;
}


